package com.zhenjiashi.sideline.cralwer.yuanjisong;

import com.zhenjiashi.sideline.entity.Jobs;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.scheduler.BloomFilterDuplicateRemover;
import us.codecraft.webmagic.scheduler.QueueScheduler;
import us.codecraft.webmagic.selector.Selectable;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class YuanjisongProcessor implements PageProcessor {

    @Override
    public void process(Page page) {
        List<Selectable> selectables = page.getHtml().css("div.consultant_title").nodes();

        List<Jobs> jobs = selectables.stream().map(selectable -> saveInfo(Jsoup.parse(selectable.get()))).collect(Collectors.toList());
        page.putField("jobs", jobs);
    }

    private Jobs saveInfo(Document document) {
        Jobs job = new Jobs();
        job.setCreateTime(new Date());
        job.setPlatform("猿急送");

        Element a = document.select("a").first();
        job.setUrl(a.attr("href"));

        Element b = a.select("b").first();
        job.setTitle(b.text());

        Element content = document.select(".glyphicon-th-large").first().parent();
        job.setContent(content.text());

        Element yen = document.select(".glyphicon-yen").first().nextElementSibling().nextElementSibling();
        job.setPrice(new BigDecimal(yen.text().replace(",", "")));

        TextNode time = (TextNode) document.select(".glyphicon-time").first().nextElementSibling().nextElementSibling().childNode(0);
        job.setDays(Long.parseLong(time.text()));
        job.setPublishTime(job.getCreateTime());
//        job.setTags();
        return job;
    }

    private Site site = Site
            .me()
            .setCharset("utf-8")
            .setTimeOut(10000)
            .setRetryTimes(3)
            .setSleepTime(3);

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider spider = Spider.create(new YuanjisongProcessor()).addUrl("https://www.yuanjisong.com/job");
        spider.setScheduler(new QueueScheduler().setDuplicateRemover(new BloomFilterDuplicateRemover(100000)));
        spider.thread(10);
        spider.run();
    }

}
